package com.nai365.nart.member.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;


/**
 * @author linco
 * @version 1.0
 * @date 2022-07-24
 * @since 1.0
 */
@Configuration
public class RabbitmqConfig {

	public static final String BLOCKCHAIN_EXCHANGE = "blockchain-exchange";

	public static final String TRANSFER_QUEUE = "blockchain.transfer";

	public static final String TRANSFER_ROUTING_KEY = "blockchain.transfer";


	@Primary
	@Bean
	public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
		final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
		rabbitTemplate.setMessageConverter(messageConverter());
		return rabbitTemplate;
	}

	@Bean
	public MessageConverter messageConverter() {
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		om.registerModule(new JavaTimeModule());
		return new Jackson2JsonMessageConverter(om);
	}


	@Bean(BLOCKCHAIN_EXCHANGE)
	public Exchange EXCHANGE_TOPICS_INFORM() {
		return ExchangeBuilder.topicExchange(BLOCKCHAIN_EXCHANGE).durable(true).build();
	}


	@Bean(TRANSFER_QUEUE)
	public Queue transferQueue() {
		return new Queue(TRANSFER_QUEUE);
	}


	@Bean
	public Binding transferQueueBinding(
			@Qualifier(TRANSFER_QUEUE) Queue queue, @Qualifier(BLOCKCHAIN_EXCHANGE) Exchange exchange) {
		return BindingBuilder.bind(queue).to(exchange).with(TRANSFER_ROUTING_KEY).noargs();
	}


}
